<template>
	<view class="face-register">
		<ob-navbar 
			title="人脸注册" 
			:show-back="true" 
			background-color="rgba(255, 255, 255, 0.95)"
			title-color="#333333"
			:border="true"
		/>
		
		<view class="register-content">
			<!-- 步骤指示器 -->
			<view class="step-indicator">
				<view class="step-item" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
					<view class="step-number">1</view>
					<text class="step-text">基本信息</text>
				</view>
				<view class="step-line" :class="{ active: currentStep > 1 }"></view>
				<view class="step-item" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
					<view class="step-number">2</view>
					<text class="step-text">人脸录入</text>
				</view>
				<view class="step-line" :class="{ active: currentStep > 2 }"></view>
				<view class="step-item" :class="{ active: currentStep >= 3 }">
					<view class="step-number">3</view>
					<text class="step-text">注册完成</text>
				</view>
			</view>
			
			<!-- 第一步：基本信息 -->
			<view v-if="currentStep === 1" class="step-content">
				<view class="form-section">
					<view class="form-title">
						<text class="title-text">填写基本信息</text>
						<text class="subtitle-text">请填写您的注册信息</text>
						<button @click="generateTestData" class="test-data-btn">生成测试数据</button>
					</view>
					
					<view class="form-group">
						<view class="input-group">
							<text class="input-label">邮箱地址</text>
							<input 
								v-model="formData.email" 
								type="text" 
								placeholder="请输入邮箱地址"
								class="input-field"
								:class="{ 'input-error': errors.email }"
								@blur="validateEmail"
								@input="clearError('email')"
							/>
							<text v-if="errors.email" class="error-text">{{ errors.email }}</text>
						</view>
						
						<view class="input-group">
							<text class="input-label">用户名</text>
							<input
								v-model="formData.username"
								type="text"
								placeholder="请输入用户名"
								class="input-field"
								:class="{ 'input-error': errors.username }"
								@blur="validateUsername"
								@input="clearError('username')"
							/>
							<text v-if="errors.username" class="error-text">{{ errors.username }}</text>
						</view>
						
						<view class="input-group">
							<text class="input-label">密码</text>
							<view class="password-wrapper">
								<input 
									v-model="formData.password" 
									:type="showPassword ? 'text' : 'password'" 
									placeholder="请输入密码"
									class="input-field password-input"
									:class="{ 'input-error': errors.password }"
									@blur="validatePassword"
									@input="clearError('password')"
								/>
								<text class="password-toggle" @click="togglePassword">
									{{ showPassword ? '隐藏' : '显示' }}
								</text>
							</view>
							<text v-if="errors.password" class="error-text">{{ errors.password }}</text>
						</view>
					</view>
					
					<view class="action-buttons">
						<button @click="goToStep2" class="next-btn">下一步</button>
					</view>
				</view>
			</view>
			
			<!-- 第二步：人脸录入 -->
			<view v-if="currentStep === 2" class="step-content">
				<view class="face-section">
					<view class="face-title">
						<text class="title-text">录入人脸信息</text>
						<text class="subtitle-text">请正对摄像头拍摄清晰的人脸照片</text>
					</view>
					
					<view class="face-capture">
						<view v-if="!faceImage" class="capture-placeholder">
							<view class="placeholder-icon">📷</view>
							<text class="placeholder-text">点击下方按钮拍摄人脸</text>
						</view>
						
						<view v-if="faceImage" class="face-preview">
							<image :src="faceImage" class="face-image" mode="aspectFit"></image>
							<view class="preview-actions">
								<button @click="retakeFace" class="retake-btn">重新拍摄</button>
							</view>
						</view>
					</view>
					
					<view class="action-buttons">
						<button @click="goToStep1" class="back-btn">上一步</button>
						<button v-if="!faceImage" @click="startFaceCapture" class="capture-btn">拍摄人脸</button>
						<button v-if="faceImage" @click="goToStep3" class="next-btn">下一步</button>
					</view>
				</view>
			</view>
			
			<!-- 第三步：注册完成 -->
			<view v-if="currentStep === 3" class="step-content">
				<view class="complete-section">
					<view class="complete-title">
						<text class="title-text">确认注册信息</text>
						<text class="subtitle-text">请确认您的注册信息无误</text>
					</view>
					
					<view class="info-summary">
						<view class="summary-item">
							<text class="summary-label">邮箱：</text>
							<text class="summary-value">{{ formData.email }}</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">用户名：</text>
							<text class="summary-value">{{ formData.username }}</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">人脸信息：</text>
							<text class="summary-value">{{ faceImage ? '已录入' : '未录入' }}</text>
						</view>
					</view>
					
					<view class="action-buttons">
						<button @click="goToStep2" class="back-btn">上一步</button>
						<button @click="completeRegistration" :disabled="isRegistering" class="complete-btn">
							{{ isRegistering ? '注册中...' : '完成注册' }}
						</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 人脸拍摄弹窗 -->
		<view v-if="showCameraModal" class="camera-modal">
			<view class="modal-overlay" @click="closeCameraModal"></view>
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">人脸拍摄</text>
					<text class="modal-close" @click="closeCameraModal">✕</text>
				</view>
				<view class="modal-body">
					<html5-camera
						:width="400"
						:height="300"
						@success="handleFaceSuccess"
						@cancel="closeCameraModal"
						@error="handleFaceError"
					/>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import Html5Camera from '../../components/face-recognition/html5-camera.vue'
import authApi from '../../api/auth.js'
import { validateEmail as validateEmailUtil } from '../../utils/common.js'

// 响应式数据
const currentStep = ref(1)
const isRegistering = ref(false)
const showPassword = ref(false)
const faceImage = ref('')
const showCameraModal = ref(false)

const formData = reactive({
	email: '',
	username: '',
	password: ''
})

// 生成随机测试数据（开发时使用）
const generateTestData = () => {
	const timestamp = Date.now()
	formData.email = `test${timestamp}@example.com`
	formData.username = `testuser${timestamp}`
	formData.password = 'password123'
}

const errors = reactive({
	email: '',
	username: '',
	password: ''
})

// 表单验证方法
const validateEmail = () => {
	errors.email = ''
	
	if (!formData.email.trim()) {
		errors.email = '请输入邮箱地址'
		return false
	}
	
	if (!validateEmailUtil(formData.email)) {
		errors.email = '请输入正确的邮箱格式'
		return false
	}
	
	return true
}

const validateUsername = () => {
	errors.username = ''
	
	if (!formData.username.trim()) {
		errors.username = '请输入用户名'
		return false
	}
	
	if (formData.username.length < 3) {
		errors.username = '用户名至少3个字符'
		return false
	}
	
	if (formData.username.length > 20) {
		errors.username = '用户名不能超过20个字符'
		return false
	}
	
	return true
}

const validatePassword = () => {
	errors.password = ''
	
	if (!formData.password.trim()) {
		errors.password = '请输入密码'
		return false
	}
	
	if (formData.password.length < 8) {
		errors.password = '密码至少8个字符'
		return false
	}
	
	if (formData.password.length > 20) {
		errors.password = '密码不能超过20个字符'
		return false
	}
	
	return true
}

const clearError = (field) => {
	errors[field] = ''
}

const togglePassword = () => {
	showPassword.value = !showPassword.value
}

// 步骤导航方法
const goToStep1 = () => {
	currentStep.value = 1
}

const goToStep2 = () => {
	// 验证第一步的表单
	if (!validateEmail() || !validateUsername() || !validatePassword()) {
		return
	}
	
	currentStep.value = 2
}

const goToStep3 = () => {
	if (!faceImage.value) {
		uni.showToast({
			title: '请先拍摄人脸照片',
			icon: 'none'
		})
		return
	}
	
	currentStep.value = 3
}

// 人脸拍摄相关方法
const startFaceCapture = () => {
	showCameraModal.value = true
}

const closeCameraModal = () => {
	showCameraModal.value = false
}

const handleFaceSuccess = (imageData) => {
	console.log('人脸拍摄成功')
	faceImage.value = imageData
	showCameraModal.value = false
	
	uni.showToast({
		title: '人脸拍摄成功',
		icon: 'success'
	})
}

const handleFaceError = (error) => {
	console.error('人脸拍摄失败:', error)
	showCameraModal.value = false
	
	uni.showToast({
		title: '拍摄失败，请重试',
		icon: 'none'
	})
}

const retakeFace = () => {
	faceImage.value = ''
}

// 完成注册
const completeRegistration = async () => {
	if (!faceImage.value) {
		uni.showToast({
			title: '请先拍摄人脸照片',
			icon: 'none'
		})
		return
	}
	
	isRegistering.value = true
	
	try {
		console.log('开始人脸注册')
		
		const response = await authApi.faceRegister({
			email: formData.email,
			username: formData.username,
			password: formData.password,
			nickname: formData.username, // 默认使用用户名作为昵称
			faceImagePath: faceImage.value
		})
		
		console.log('人脸注册响应:', response)
		
		if (response && response.success) {
			uni.showToast({
				title: '注册成功',
				icon: 'success',
				duration: 1500
			})
			
			// 延迟跳转到登录页面
			setTimeout(() => {
				uni.redirectTo({
					url: '/pages/auth/face-login'
				})
			}, 1500)
		} else {
			throw new Error(response.message || '注册失败，请重试')
		}
		
	} catch (error) {
		console.error('注册失败:', error)

		let errorMessage = '注册失败，请重试'
		if (error.message) {
			if (error.message.includes('邮箱已被注册')) {
				errorMessage = '该邮箱已被注册，请使用其他邮箱'
				// 回到第一步让用户修改邮箱
				currentStep.value = 1
				errors.email = '该邮箱已被注册'
			} else if (error.message.includes('用户名已被使用')) {
				errorMessage = '该用户名已被使用，请使用其他用户名'
				// 回到第一步让用户修改用户名
				currentStep.value = 1
				errors.username = '该用户名已被使用'
			} else if (error.message.includes('资源冲突')) {
				errorMessage = '用户名或邮箱已存在，请检查后重试'
				currentStep.value = 1
			} else {
				errorMessage = error.message
			}
		}

		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 3000
		})
	} finally {
		isRegistering.value = false
	}
}
</script>

<style lang="scss" scoped>
.face-register {
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-content {
	padding: 20px;
}

// 步骤指示器
.step-indicator {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 30px;
	background: rgba(255, 255, 255, 0.1);
	padding: 20px;
	border-radius: 16px;
	backdrop-filter: blur(10px);
}

.step-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;

	&.active .step-number {
		background: #007AFF;
		color: #ffffff;
	}

	&.completed .step-number {
		background: #28a745;
		color: #ffffff;
	}
}

.step-number {
	width: 32px;
	height: 32px;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.3);
	color: #ffffff;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	font-weight: 600;
	margin-bottom: 8px;
}

.step-text {
	font-size: 12px;
	color: #ffffff;
	opacity: 0.8;
}

.step-line {
	width: 60px;
	height: 2px;
	background: rgba(255, 255, 255, 0.3);
	margin: 0 20px;

	&.active {
		background: #007AFF;
	}
}

// 步骤内容
.step-content {
	background: #ffffff;
	border-radius: 20px;
	padding: 30px 20px;
	box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

// 表单部分
.form-title, .face-title, .complete-title {
	text-align: center;
	margin-bottom: 30px;
}

.title-text {
	display: block;
	font-size: 24px;
	font-weight: 700;
	color: #333333;
	margin-bottom: 8px;
}

.subtitle-text {
	display: block;
	font-size: 14px;
	color: #666666;
}

.test-data-btn {
	margin-top: 12px;
	padding: 6px 12px;
	background: #17a2b8;
	color: #ffffff;
	border: none;
	border-radius: 6px;
	font-size: 12px;
}

.form-group {
	margin-bottom: 30px;
}

.input-group {
	margin-bottom: 20px;
}

.input-label {
	display: block;
	font-size: 14px;
	font-weight: 600;
	color: #333333;
	margin-bottom: 8px;
}

.input-field {
	width: 100%;
	height: 48px;
	background: #f8f9fa;
	border: 2px solid #e9ecef;
	border-radius: 12px;
	padding: 0 16px;
	font-size: 16px;
	color: #333333;
	transition: all 0.3s ease;

	&:focus {
		border-color: #007AFF;
		background: #ffffff;
		outline: none;
	}

	&.input-error {
		border-color: #dc3545;
		background: #fff5f5;
	}
}

.password-wrapper {
	position: relative;
}

.password-input {
	padding-right: 60px;
}

.password-toggle {
	position: absolute;
	right: 16px;
	top: 50%;
	transform: translateY(-50%);
	font-size: 14px;
	color: #007AFF;
	cursor: pointer;
}

.error-text {
	display: block;
	font-size: 12px;
	color: #dc3545;
	margin-top: 4px;
}

// 人脸拍摄部分
.face-capture {
	margin-bottom: 30px;
}

.capture-placeholder {
	height: 200px;
	background: #f8f9fa;
	border: 2px dashed #dee2e6;
	border-radius: 12px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.placeholder-icon {
	font-size: 48px;
	margin-bottom: 12px;
}

.placeholder-text {
	font-size: 14px;
	color: #666666;
}

.face-preview {
	text-align: center;
}

.face-image {
	width: 200px;
	height: 150px;
	border-radius: 12px;
	margin-bottom: 16px;
}

.preview-actions {
	margin-bottom: 16px;
}

.retake-btn {
	background: #6c757d;
	color: #ffffff;
	border: none;
	border-radius: 8px;
	padding: 8px 16px;
	font-size: 14px;
}

// 信息摘要
.info-summary {
	background: #f8f9fa;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 30px;
}

.summary-item {
	display: flex;
	justify-content: space-between;
	margin-bottom: 12px;

	&:last-child {
		margin-bottom: 0;
	}
}

.summary-label {
	font-size: 14px;
	color: #666666;
}

.summary-value {
	font-size: 14px;
	color: #333333;
	font-weight: 500;
}

// 操作按钮
.action-buttons {
	display: flex;
	gap: 12px;
}

.back-btn, .next-btn, .capture-btn, .complete-btn {
	flex: 1;
	height: 48px;
	border: none;
	border-radius: 12px;
	font-size: 16px;
	font-weight: 600;
	transition: all 0.3s ease;
}

.back-btn {
	background: #6c757d;
	color: #ffffff;
}

.next-btn, .complete-btn {
	background: #007AFF;
	color: #ffffff;

	&:disabled {
		background: #6c757d;
		opacity: 0.6;
	}
}

.capture-btn {
	background: #28a745;
	color: #ffffff;
}

// 摄像头弹窗
.camera-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.modal-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.7);
}

.modal-content {
	position: relative;
	background: #ffffff;
	border-radius: 16px;
	padding: 0;
	max-width: 90%;
	max-height: 90%;
	overflow: hidden;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px 20px;
	border-bottom: 1px solid #e9ecef;
}

.modal-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.modal-close {
	font-size: 20px;
	color: #666666;
	cursor: pointer;
}

.modal-body {
	padding: 20px;
}
</style>
